<?php

namespace App\Http\Controllers\WebApp\Api;

use App\Exceptions\ApiException;
use App\Http\Resources\DeviceResource;
use App\Http\Resources\DevicesResource;
use App\Tables\Device;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;

class DeviceController extends Controller
{
    /**
     * 查询设备列表
     * @param Request $request
     * @return DevicesResource
     */
    public function index(Request $request)
    {
        $query = new Device();

        $this->validate($request, [
            'lat' => 'required',
            'lng' => 'required'
        ],[],[
            'lat' => '经度',
            'lng' => '纬度'
        ]);

        $distance_raw = DB::raw("(st_distance(coordinate, point({$request->lat},{$request->lng})) * 111195) AS distance");

        $query = $query->newQuery(true)->addSelect($distance_raw);

        if ($request->filled('range')) {
            $query = $query->having('distance', '<=', $request->range);
        }

        $query = $query->orderBy(DB::raw('distance'));

        /**
         * 分页
         */
        $page = $request->get('page', 1);
        $pageSize = $request->header('pageSize') ?: $request->get('pageSize', 50);

        $skip = $pageSize * ($page - 1);
        $data = $query->skip($skip)->take($pageSize)->get();

        $data = array_map(function ($item) {
            return collect($item)->only(['id', 'device_sn', 'full_address', 'name', 'remark', 'status', 'status_text', 'ports', 'ladder_price', 'coordinate', 'distance']);
        }, $data->toArray());

        return response()->json(ajax_return(true, 'ok', $data));
    }


    /**
     * 获取设备信息详情
     * @param $device_sn
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiException
     */
    public function detail($device_sn)
    {
        $device = Device::where('device_sn', $device_sn)->first();

        if (empty($device)) {
            throw new ApiException('设备信息不存在');
        }

        $device->need_max_money = bcmul($device->ladder_price['four']['price'], config('system.superpower_multiple', 1), 2);
        $device->superpower_multiple = config('system.superpower_multiple', 1);

        return response()->json(ajax_return(true, '获取设备信息成功', new DeviceResource($device)));
    }
}
